<template>
  <div class="maintenance-list">
    <div v-show="!dialogFalgFull">
      <el-row type="flex" justify="space-between">
        <el-form :inline="true" ref="formInline" :model="formInline" class="demo-form-inline" @submit.native.prevent>
          <el-form-item v-if="isMuilUnitUser">
            <el-select filterable @change="orgIdchange" v-model="formInline.orgIds" placeholder="请选择业主单位">
              <el-option
                v-for="item in orgOptions"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="formInline.time"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="util.intTimePickerOptions()"
              @change="getData(1)"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item>
              <el-select 
                filterable 
                @change="getData(1)" 
                v-model="formInline.maintenanceTyle" 
                placeholder="维保类型">
                <el-option
                  v-for="item in maintenanceTyleList"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>-->
          <el-form-item>
            <el-select filterable @change="getData(1)" v-model="formInline.allType" placeholder="请选择状态">
              <el-option v-for="item in allTypeList" :key="item.value" :label="item.key" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item>
              <el-select 
                filterable 
                @change="getData(1)"
                v-model="formInline.inputType" 
                placeholder="">
                <el-option
                  v-for="item in inputTypeList"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>-->
          <el-form-item>
            <el-select filterable @change="getData(1)" v-model="formInline.workPeriod" placeholder="请选择维保周期">
              <el-option v-for="item in workPeriodList" :key="item.value" :label="item.key" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select filterable @change="getData(1)" v-model="formInline.maintainAccount" placeholder="请选择维保人员">
              <el-option label="全部维保人员" value></el-option>
              <el-option
                v-for="item in maintainAccountOptions"
                :key="item.accountName"
                :label="item.name"
                :value="item.accountName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input placeholder="请输入任务名称" v-model="formInline.content" clearable @keyup.enter.native="getData(1)"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="form-search-btn" type="primary" @click="getData(1)">查询</el-button>
          </el-form-item>
        </el-form>
        <div
          class="more-btns"
          v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('toMainPeople') > -1"
        >
          <el-button type="primary" @click="designProvider()">批量指定维保人</el-button>
        </div>
      </el-row>
      <el-row class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
        <span style="display:none;">{{freashStaticFlag}}</span>
        <el-col :span="6">
          <div
            class="item-wrap"
            @click="formInline.maintenanceTyle=''"
            :class="formInline.maintenanceTyle=='' ? 'active' : ''"
          >
            <div class="item-content">
              <p class="item-value color-3">{{ staticObj.totalNum }}</p>
              <p class="item-title">全部任务（个）</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div
            class="item-wrap"
            @click="formInline.maintenanceTyle='1'"
            :class="formInline.maintenanceTyle==1 ? 'active' : ''"
          >
            <div class="item-content">
              <p class="item-value color-6">{{ staticObj.patrolNum}}</p>
              <p class="item-title">维保巡查（个）</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div
            class="item-wrap"
            @click="formInline.maintenanceTyle='2'"
            :class="formInline.maintenanceTyle==2 ? 'active' : ''"
          >
            <div class="item-content">
              <p class="item-value color-8">{{ staticObj.maintainNum }}</p>
              <p class="item-title">保养（个）</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div
            class="item-wrap"
            @click="formInline.maintenanceTyle='3'"
            :class="formInline.maintenanceTyle==3 ? 'active' : ''"
          >
            <div class="item-content">
              <p class="item-value color-4">{{ staticObj.testNum }}</p>
              <p class="item-title">单点测试（个）</p>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div
            class="item-wrap"
            @click="formInline.maintenanceTyle='4'"
            :class="formInline.maintenanceTyle==4 ? 'active' : ''"
          >
            <div class="item-content">
              <p class="item-value color-5">{{ staticObj.unionTestNum }}</p>
              <p class="item-title">联动测试（个）</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <div>
        <el-table
          v-loading="loading"
          :data="maintenceTableData"
          ref="maintenceTableData"
          style="width: 100%"
          @select-all="checkRowAll"
          @select="checkRow"
        >
          <el-table-column
            v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('toMainPeople') > -1"
            :selectable="hasCheckbox"
            type="selection"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column prop="orgName" label="业主单位"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="props">
              <div v-html="util.transMaintenceStatus(props.row.status)"></div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="任务名称"></el-table-column>
          <el-table-column prop="maintainTypeName" label="维保类型" width="150">
            <template slot-scope="props">
              <div v-if="props.row.maintainType == 1">维保巡查</div>
              <div v-if="props.row.maintainType == 2">保养</div>
              <div v-if="props.row.maintainType == 3">单点测试</div>
              <div v-if="props.row.maintainType == 4">联动测试</div>
            </template>
          </el-table-column>
          <el-table-column label="维保周期" prop="workPeriod" width="100">
            <template slot-scope="scope">
              <p v-if="scope.row.workPeriod == 1">月</p>
              <p v-else-if="scope.row.workPeriod == 2">季度</p>
              <p v-else-if="scope.row.workPeriod == 3">半年</p>
              <p v-else-if="scope.row.workPeriod == 4">1年</p>
              <p v-else>-</p>
            </template>
          </el-table-column>
          <el-table-column prop="assetsCount" label="资产数量" width="100"></el-table-column>
          <el-table-column label="开始日期">
            <template slot-scope="props">{{ formatDateTime(props.row.startTime) }}</template>
          </el-table-column>
          <el-table-column label="结束日期">
            <template slot-scope="props">{{ formatDateTime(props.row.endTime) }}</template>
          </el-table-column>
          <el-table-column prop="maintainNames" label="维保人"></el-table-column>
          <el-table-column label="完成进度" width="250">
            <template slot-scope="props">
              <el-progress
                text-inside
                :stroke-width="20"
                :percentage="util.completionDegree(props.row.finishCount,props.row.assetsCount)"
              ></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="props">
              <el-button type="text" size="small" @click="handleDetail(props.row)">详情</el-button>
              <template v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('toMainPeople') > -1">
                <span v-if="props.row.status == 1 || props.row.status == 2" class="dividing-line">|</span>
                <el-button
                  v-if="props.row.status == 1 || props.row.status == 2"
                  type="text"
                  size="small"
                  @click="designProvider(props.row)"
                >指定维保人</el-button>
              </template>
            </template>
          </el-table-column>
          <el-table-column type="expand" width="1">
            <template slot-scope="props">
              <el-tabs type="border-card">
                <el-tab-pane name>
                  <span slot="label">详情</span>
                  <div v-if="openDeatil[props.row.id] && openDeatil[props.row.id].length > 0" class="block">
                    <el-timeline>
                      <template v-for="item in openDeatil[props.row.id]">
                        <el-timeline-item
                          v-if="item.maintainAccount != ''"
                          :timestamp="item.startTime"
                          :key="item.id"
                          placement="top"
                        >
                          <div v-if="item.maintainName">
                            <el-card>
                              <div class="maintence-detail-title">
                                <b>作业对象</b>：
                                <span>{{ item.workObject }}</span>
                              </div>
                              <div class="maintence-detail-title">
                                <b>维保人员</b>：
                                <span>{{ item.maintainName }}</span>
                              </div>
                              <p>
                                <b>作业前照片</b>：
                              </p>
                              <div class="block maintence-work-pic">
                                <div v-if="item.picBeforeUrls">
                                  <template v-for="(obj,i) in item.picBeforeUrls.split(',')">
                                    <img
                                      v-if="'mp4,3gp,mpeg,mavip4,mov,flv'.includes(obj.split('.')[obj.split('.').length - 1].toLowerCase())"
                                      :key="i"
                                      :src="require('@/assets/images/video/video-detail.png')"
                                      width="100"
                                      height="100"
                                      @click="$imgViewer"
                                      :data-imgpreview="item.picBeforeUrls"
                                      :data-imgpreviewindex="i"
                                    />
                                    <img
                                      v-else
                                      :key="i"
                                      :src="obj||defaultImg"
                                      width="100"
                                      height="100"
                                      @click="$imgViewer"
                                      :data-imgpreview="item.picBeforeUrls"
                                      :data-imgpreviewindex="i"
                                    />
                                  </template>
                                </div>
                                <div v-else>
                                  <template>无</template>
                                </div>
                              </div>
                              <p>
                                <b>作业后照片</b>：
                              </p>
                              <div class="block maintence-work-pic">
                                <div v-if="item.picAfterUrls">
                                  <template v-for="(obj,i) in item.picAfterUrls.split(',')">
                                    <img
                                      v-if="'mp4,3gp,mpeg,mavip4,mov,flv'.includes(obj.split('.')[obj.split('.').length - 1].toLowerCase())"
                                      :key="i"
                                      :src="require('@/assets/images/video/video-detail.png')"
                                      @click="$imgViewer"
                                      :data-imgpreview="item.picAfterUrls"
                                      :data-imgpreviewindex="i"
                                    />
                                    <img
                                      v-else
                                      :key="i"
                                      :src="obj||defaultImg"
                                      width="100"
                                      height="100"
                                      @click="$imgViewer"
                                      :data-imgpreview="item.picAfterUrls"
                                      :data-imgpreviewindex="i"
                                    />
                                  </template>
                                </div>
                                <div v-else>
                                  <template>无</template>
                                </div>
                              </div>
                              <p v-if="item.maintainStandardContent">
                                <b>作业填报</b>：
                              </p>
                              <el-row v-if="item.maintainStandardContent">
                                <el-col
                                  v-for="(obj, i) in item.maintainStandardContent"
                                  :key="obj.id"
                                  :span="24"
                                  class="work-item"
                                >
                                  <p>
                                    <span class="maintain-standard-index">{{i+1}}</span>
                                    {{obj.workContent}}
                                  </p>
                                  <!-- 工作结果类型分类 -->
                                  <p
                                    class="maintain-standard-result"
                                  >工作结果：{{ transWork(obj.type,item.description,obj.id) }}</p>
                                </el-col>
                              </el-row>
                            </el-card>
                          </div>
                        </el-timeline-item>
                      </template>
                    </el-timeline>
                  </div>
                  <div v-else>暂无数据</div>
                </el-tab-pane>
              </el-tabs>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="sizeChange"
          @current-change="pageChange"
          :current-page="formInline.currentPageIndex"
          :page-sizes="[10, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formInline.currentPageTotal"
        ></el-pagination>
        <el-dialog
          :close-on-click-modal="false"
          title="指定维保人"
          width="600px"
          top="10vh"
          v-if="dialogFalg"
          :visible.sync="dialogFalg"
          v-dialogDrag
          @close="closeDialog"
        >
          <edit-maintence :scopeRow="scopeRow" :multipleCheck="multipleCheck" :closeDialog="closeDialog"></edit-maintence>
        </el-dialog>
      </div>
    </div>
    <transition name="el-zoom-in-top">
      <single-maintenance-task
        v-if="dialogFalgFull"
        :organizationId="singleOrgId"
        :organizationName="singleOrgName"
        :hasFather="hasFather"
        :backFather="backFather"
        :queryObj="queryStringObj"
      ></single-maintenance-task>
    </transition>
  </div>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import EditMaintence from '../Dialog/EditMaintence'
import SingleMaintenanceTask from './SingleMaintenanceTask'
import util from '@/utils/util'
import { getOrgList } from '@/api/org'
import {
  getMaintenceList,
  statMaintainTask,
  getMaintainTaskDetailByTaskId,
  getHaveOrgUserList,
} from '@/api/maintence'

export default {
  name: 'MoreMaintenanceTask',
  components: {
    TreeSelect,
    EditMaintence,
    SingleMaintenanceTask,
  },
  props: {
    organizationIds: {
      type: String,
      required: true,
    },
    // 页面跳转附带的参数
    queryObj: {
      default() {
        return false
      },
    },
  },
  data() {
    return {
      queryStringObj: this.queryObj,
      msg: '维保页面',
      freashStaticFlag: 0,
      util: util,
      isMuilUnitUser: this.$store.state.userinfo.isMuilUnitUser,
      maintainAccountOptions: [],
      formInline: {
        orgIds: this.$store.state.userinfo.isMuilUnitUser
          ? this.$store.state.userinfo.organizationIds
          : this.$store.state.userinfo.org.id,
        time: '',
        content: '',
        maintenanceTyle: '',
        allType: '',
        inputType: '1',
        workPeriod: '-1',
        maintainAccount: '', // 维保人员
        currentPageSize: 10,
        currentPageIndex: 1,
        currentPageTotal: 0,
      },
      staticObj: {
        // 数量统计
        totalNum: 0,
        maintainNum: 0,
        testNum: 0,
        patrolNum: 0,
        unionTestNum: 0,
      },
      loading: false,
      dialogFalg: false,
      dialogFalgFull: false,
      maintenceTableData: [],
      scopeRow: {}, // 编辑对应行数据
      orgOptions: [
        {
          organizationId: this.$store.state.userinfo.organizationIds,
          shortName: '全部业主单位',
        },
      ],
      maintenanceTyleList: [
        { value: '', key: '全部维保类型' },
        { value: '1', key: '维保巡查' },
        { value: '2', key: '保养' },
        { value: '3', key: '单点测试' },
        { value: '4', key: '联动测试' },
      ],
      allTypeList: [
        { value: '', key: '全部状态' },
        { value: '1', key: '未开始' },
        { value: '2', key: '进行中' },
        { value: '3', key: '已结束' },
      ],
      inputTypeList: [
        { value: '1', key: '名称' },
        { value: '2', key: '维保人' },
        { value: '3', key: '业主单位' },
      ],
      workPeriodList: [
        { value: '-1', key: '全部维保周期' },
        { value: '1', key: '月' },
        { value: '2', key: '季度' },
        { value: '3', key: '半年' },
        { value: '4', key: '1年' },
      ],
      multipleCheck: [],
      hasFather: true,
      singleOrgId: 0,
      singleOrgName: '',
      openDeatil: {},
      // openDeatilLength:0,
      exloading: false,
    }
  },
  created() {
    //绑定下拉框
    if (this.isMuilUnitUser) {
      getOrgList({ queryType: 0 }).then((data) => {
        this.orgOptions.push.apply(this.orgOptions, data.data)
        this.getMaintainUser()
      })
    }
    this.init()
  },
  methods: {
    init() {
      // 是否有页面跳转的查询参数
      if (this.queryObj) {
        this.singleOrgName = this.queryObj.orgName

        if (this.queryObj.level == 1) {
          this.dialogFalgFull = false
          this.formInline.orgIds = this.queryObj.orgId
        } else {
          this.dialogFalgFull = true
          this.singleOrgId = this.queryObj.orgId
        }

        this.formInline.content = this.queryObj.systomType
        this.formInline.maintenanceTyle = this.queryObj.fireTTypes
        if (this.queryObj.time) {
          let startTime = this.queryObj.time + '-01 00:00:00'
          let endTime =
            this.queryObj.time +
            '-' +
            new Date(
              this.queryObj.time.substring(0, 4),
              this.queryObj.time.substring(5, 7),
              0
            ).getDate() +
            ' 23:59:59'
          this.formInline.time = [startTime, endTime]
        }
      }

      this.getStatis()
      this.getList()
    },
    // 单位选择切换
    orgIdchange() {
      this.formInline.maintainAccount = ''
      this.getMaintainUser()
      this.getData(1)
    },
    // 获取维保人员数据
    getMaintainUser() {
      getHaveOrgUserList({
        orgIds: this.formInline.orgIds,
        roleIds: '185,184,183',
      }).then((res) => {
        this.maintainAccountOptions = res.data.length > 0 ? res.data : []
      })
    },
    hasCheckbox(row, index) {
      if (row.status == 1 || row.status == 2) {
        return true
      } else {
        return false
      }
    },
    formatDateTime: function (time) {
      return time.split(' ')[0]
    },
    //获取头部统计
    getStatis: function () {
      //this.staticObj = {}
      let startTime = ''
      let endTime = ''
      if (
        this.formInline.time &&
        this.formInline.time.length &&
        this.formInline.time.length > 0
      ) {
        startTime = this.formInline.time[0]
        endTime = this.formInline.time[1]
      }
      statMaintainTask({
        startTime: startTime,
        endTime: endTime,
        orgIds:
          this.formInline.orgIds || this.$store.state.userinfo.organizationIds,
        categoryIds: '',
        maintainType: '' /* this.formInline.maintenanceTyle */,
        status: this.formInline.allType || '',
        name: (this.formInline.content || '').trim(),
        nameType: this.formInline.inputType || '',
        workPeriod: this.formInline.workPeriod || '-1',
        maintainAccount: this.formInline.maintainAccount || '',
      }).then((result) => {
        $.extend(this.staticObj, result.data)
        this.freashStaticFlag++
      })
    },
    //页码切换
    sizeChange(val) {
      this.formInline.currentPageIndex = 1
      this.formInline.currentPageSize = val
      this.getList()
    },
    //翻页
    pageChange(val) {
      this.formInline.currentPageIndex = val
      this.getList()
    },
    //全选
    checkRowAll(val) {
      let self = this
      let orgIds = []
      self.multipleCheck = []
      if (val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          this.multipleCheck.push(val[i].id)
        }
        this.scopeRow = val
      }
    },
    //勾选行数据
    checkRow(val) {
      this.multipleCheck = []
      if (val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          this.multipleCheck.push(val[i].id)
        }
        this.scopeRow = val
      }
    },
    //获取列表信息
    getList: function (_pageIndex) {
      if (_pageIndex) {
        this.formInline.currentPageIndex = _pageIndex
      }
      this.loading = true
      let startTime = ''
      let endTime = ''
      if (
        this.formInline.time &&
        this.formInline.time.length &&
        this.formInline.time.length > 0
      ) {
        startTime = this.formInline.time[0]
        endTime = this.formInline.time[1]
      }
      getMaintenceList({
        startTime: startTime,
        endTime: endTime,
        orgIds:
          this.formInline.orgIds || this.$store.state.userinfo.organizationIds,
        categoryIds: '',
        maintainType: this.formInline.maintenanceTyle || '',
        status: this.formInline.allType || '',
        name: (this.formInline.content || '').trim(),
        nameType: this.formInline.inputType || '',
        workPeriod: this.formInline.workPeriod || '-1',
        maintainAccount: this.formInline.maintainAccount || '',
        queryType: 1,
        pageIndex: this.formInline.currentPageIndex - 1,
        pageSize: this.formInline.currentPageSize,
      }).then((result) => {
        this.formInline.currentPageTotal = result.total
        this.maintenceTableData = result.data
        this.loading = false
      })
    },
    //查询
    getData: function (_pageIndex) {
      this.getStatis()
      this.getList(_pageIndex)
    },
    //指定维保人
    designProvider: function (row) {
      if (row) {
        this.dialogFalg = true
        this.scopeRow = row || {}
      } else {
        if (this.multipleCheck.length == 0) {
          this.$message({
            message: '请勾选维保任务',
            type: 'warning',
          })
        } else {
          let orgIds = []
          let isHasSameOrgId = false
          for (let i = 0; i < this.scopeRow.length; i++) {
            if (i > 0) {
              if (orgIds.indexOf(this.scopeRow[i].orgId) != -1) {
                orgIds.push(this.scopeRow[i].orgId)
              } else {
                isHasSameOrgId = true
                break
              }
            } else {
              orgIds.push(this.scopeRow[i].orgId)
            }
          }
          if (isHasSameOrgId) {
            this.$message({
              message: '请选择相同单位指定维保人',
              type: 'warning',
            })
          } else {
            this.dialogFalg = true
          }
        }
      }
    },
    closeDialog(refresh) {
      this.dialogFalg = false
      if (typeof refresh === 'boolean' && refresh) {
        this.getList()
      }
    },
    // 列表详情
    handleDetail(row) {
      let self = this
      let newArr = []
      row.isExpand = !row.isExpand //给row一个自定义展开状态
      if (row && row.isExpand) {
        self.exloading = true
        getMaintainTaskDetailByTaskId({
          id: row.id,
        }).then((res) => {
          let noData = true //详情是否有数据标识
          if (res.status == 200 && res.data.length > 0) {
            for (var i = 0; i < res.data.length; i++) {
              if (res.data[i].maintainAccount != '') {
                noData = false
                break
              }
            }
            if (!noData) {
              newArr = res.data
            }
            self.$set(self.openDeatil, row.id, newArr, 'maintainAccount')
            // self.openDeatilLength = self.openDeatil[row.id].length;
          } else {
            // self.openDeatilLength = 0;
          }
          self.exloading = false
        })
      }
      self.$refs.maintenceTableData.toggleRowExpansion(row)
    },
    backFather() {
      this.queryStringObj = false
      this.dialogFalgFull = false
    },
    // 单点型资产维保结果映射
    maintainStandardResultMap(code) {
      const ResultMAP = {
        0: '正常',
        1: '异常',
        2: '未涉及',
      }
      return ResultMAP[code] || ''
    },
    //解析作业填报提交结果
    transWork(type, content, objId) {
      let tab = ''
      let html1 = ''
      let html2 = ''
      let des = JSON.parse(content)
      if (des[objId].tab) {
        tab = this.maintainStandardResultMap(des[objId].tab)
      }
      if (des[objId].des) {
        html1 = '  ' + des[objId].des
      }
      if (des[objId].num) {
        html2 = '  ' + des[objId].num
      }
      return tab + html1 + html2
    },
  },
  watch: {
    queryObj(val) {
      if (val.level) {
        this.init()
      }
    },
    handlerStatusSelect(val, oldVal) {
      if (val !== oldVal) {
        this.getList(1)
      }
    },
  },
  computed: {
    handlerStatusSelect() {
      return this.formInline.maintenanceTyle
    },
  },
}
</script>

<style lang="less">
.maintenance-list {
  position: relative;
  margin: 10px;
  margin-bottom: 20px;
  margin-top: 0px;
  .title {
    padding-bottom: 10px;
  }
  .maintence-detail-title {
    margin: 10px 0;
  }
  .maintence-work-pic {
    img {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
</style>
